
puts '[info] begin to aggregate the given score file by max...'

exit 0 if ARGV[0] == nil
workingDir = ARGV[0]
sortedInputFile = ARGV[1]
aggregatedOutputFile = "#{sortedInputFile}_max"


begin
    ratingFile_sorted = File.open("#{workingDir}/#{sortedInputFile}", 'r')
    ratingFile_aggregated = File.open("#{workingDir}/#{aggregatedOutputFile}", 'w')
    curUid = 0
    curPid = 0
    curRating = 0
    curTime = ''
    nextUid = 0
    nextPid = 0
    nextRating = 0
    nextTime = ''
    ratingFile_sorted.each_line { |line|
        arr = line.split("\t")
        nextUid = arr[0].strip.to_i
        nextPid = arr[1].strip.to_i
        nextRating = arr[2].strip.to_i
        nextTime = arr[3].strip
        if nextUid!=0 && nextPid!=0 && nextRating!=0
            if nextUid==curUid && nextPid==curPid
                curRating = nextRating if nextRating > curRating
                curTime = nextTime if nextRating > curRating
            else
                ratingFile_aggregated.write("#{curUid.to_s}\t#{curPid.to_s}\t#{curRating.to_s}\t#{curTime}\n") if curUid!=0 && curPid!=0
                curUid = nextUid
                curPid = nextPid
                curRating = nextRating
                curTime = nextTime
            end
        end
    }
    ratingFile_aggregated.write("#{curUid.to_s}\t#{curPid.to_s}\t#{curRating.to_s}\t#{curTime}\n") if curUid!=0 && curPid!=0
ensure
    ratingFile_sorted.close if ratingFile_sorted != nil
    ratingFile_aggregated.close if ratingFile_aggregated != nil
end

puts '[info] Job is done !!!'
